package com.ums.upos.util;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;

import com.ums.upos.GlobalDataHolder;
import com.ums.upos.uapi.ServiceResult;
import com.xinguodu.ddiinterface.Ddi;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by 白小峰 on 2018/4/8 0008.
 */

public class DeviceUtils {

    private static final int REQUEST_PHONE_STATE = 1;
    /**
     * 获取产品名称
     */
    public static String getProdactName() {
        return Build.MODEL;
    }

    /**
     * 获取机器序列号（sn）
     */
    public static String getSn() {
        return GlobalDataHolder.getInstance().getSn();
    }

    /**
     * 获取android 系统版本号
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取系统Android基带版本
     */
    public static String getBasebandVersion() {
        String version = "";
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Object object = clazz.newInstance();
            Method method = clazz.getMethod("get", new Class[]{String.class, String.class});
            Object result = method.invoke(object, new Object[]{"gsm.version.baseband", "no message"});
            version = (String) result;
        } catch (Exception e) {
        }
        return version;
    }

    /**
     * 获取Boot版本号
     */
    public static String getBootVersion() {
        byte[] k21ver = new byte[17];
        Ddi.ddi_sys_get_firmwarever(k21ver, 2);
        String k21verstr = new String(k21ver);
        return k21verstr;
    }

    //系统时间转换成 00：00：00
    public static String secToTime(long time) {
        String timeStr = null;
        long hour = 0;
        long minute = 0;
        long second = 0;
        if (time <= 0)
            return "00:00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                /*if (hour > 99)
                    return "99:59:59";*/
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(long i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Long.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }


    /**
     * 获取Android 内核版本号
     */
    public static String getKernelVersion() {
        String kernelVersion = "";
        InputStream inputStream;
        try {
            inputStream = new FileInputStream("/proc/version");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return kernelVersion;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
        String info = "";
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                info += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (info != "") {
                final String keyword = "version ";
                int index = info.indexOf(keyword);
                line = info.substring(index + keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        return kernelVersion;
    }

    /**
     * 获取SDK版本
     */
    public static String getSDKVersion() {
        return Build.VERSION.SDK_INT + "";
    }

    /**
     * 获取IMEI 号
     */
    public static String getIMEI(Context context) {

        String imei = "";
        try {
            //判断权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_PHONE_STATE);
            } else {
                TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
                imei = telephonyMgr.getImei();
            }
            }catch(Exception e){
                e.printStackTrace();
            }

            return imei;
    }

    /**
     * 获取MEID 号
     * @return MEID
     */
    public static String getMEID(Context activity) {
        String meid = "";
        try {
            TelephonyManager telephonyMgr = (TelephonyManager) activity.getSystemService(TELEPHONY_SERVICE);
            Method method = telephonyMgr.getClass().getMethod("getDeviceId", int.class);
            meid = (String) method.invoke(telephonyMgr, 1);

            if(meid.equals(getIMEI(activity))){
                meid="";
            }
        } catch (Exception e) {
        }

        return meid;
    }

    /**
     * 获取屏幕信息
     */
    public static String getScreenInfo(Context activity) {

        DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
        //获取屏幕宽度的物理像素格式
        int widthPix = metrics.widthPixels;
        //获取屏幕高度的物理像素格式
        int heightPix = metrics.heightPixels;

        return widthPix+"x"+heightPix;
    }


    /**
     * 获取MAC地址(wifi)
     */
    public static String getMacWifiAddress(Context mContext) {

        String macStr = "";
        WifiManager wifiManager = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getMacAddress() != null) {
            macStr = wifiInfo.getMacAddress();// MAC地址
        }

        return macStr;
    }

    /**
     * 获取mac地址(蓝牙)
     */
    public static String getMacBToothAddress() {
        BluetoothAdapter btAda = BluetoothAdapter.getDefaultAdapter();
        //开启蓝牙
        if (btAda.isEnabled() == false) {
            if (btAda.enable()) {
                while (btAda.getState() == BluetoothAdapter.STATE_TURNING_ON
                        || btAda.getState() != BluetoothAdapter.STATE_ON) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return btAda.getAddress();
    }


    /**
     * 获取CPU信息
     */
    public static String getCpuInfo() {

        String str1 = "/proc/cpuinfo";
        String str2 ;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr);
            while ((str2=localBufferedReader.readLine()) != null) {
                if (str2.contains("Hardware")) {
                    return str2.split(":")[1];
                }
            }
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return null;

    }

    /**
     * CPU型号
     * @return
     */
    public static String getCpuModel(){

        String  cpuInfo = getCpuInfo();
        if(!cpuInfo.equals("")){
            cpuInfo = cpuInfo.substring(cpuInfo.length()-7,cpuInfo.length());
        }
        return cpuInfo;
    }


    /**
     * 获取CPU的最大频率（mHz）
     * @return CPU的信息
     */
    public static String  getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }

        return Integer.parseInt(result.trim())/1000000+"G赫兹";
    }


    /**
     * 摄像头信息
     * @param paramInt
     * @return
     */
    public static int getCameraPixels(int paramInt) {

        if(paramInt ==1){
            int numCameras = Camera.getNumberOfCameras();
            if (numCameras == 1)
                return 0;
        }
        Camera localCamera = Camera.open(paramInt);
        Camera.Parameters localParameters = localCamera.getParameters();
        localParameters.set("camera-id", 1);
        List<Camera.Size> localList = localParameters.getSupportedPictureSizes();
        if (localList != null) {
            int heights[] = new int[localList.size()];
            int widths[] = new int[localList.size()];
            for (int i = 0; i < localList.size(); i++) {
                Camera.Size size = (Camera.Size) localList.get(i);
                int sizehieght = size.height;
                int sizewidth = size.width;
                heights[i] = sizehieght;
                widths[i] = sizewidth;
            }
            int pixels = getMaxNumber(heights) * getMaxNumber(widths);
            localCamera.release();
            return pixels / 10000;

        } else return 0;

    }

    public static int getMaxNumber(int[] paramArray) {
        int temp = paramArray[0];
        for (int i = 0; i < paramArray.length; i++) {
            if (temp < paramArray[i]) {
                temp = paramArray[i];
            }
        }
        return temp;
    }

    /**
     * 获取（RAM）运存总容量
     */
    public static long getRamTotal(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return initial_memory;
    }

    /**
     * 获取（RAM）可用运存大小
     */
    public static long getRamAvail(Context context) {
        // 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        //mi.availMem; 当前系统的可用内存
        long ramAvail = mi.availMem;
        return ramAvail;
    }

    /**
     * 获得ROM总大小
     * @return
     */
    public static String  getRomTotal() {

        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return blockSize * totalBlocks+"";
    }

    /**
     * 获得ROM可用大小
     * @return
     */
    public static String getRomAvail() {

        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return blockSize * availableBlocks+"";
    }

    /**
     * 获得SD卡总大小
     * @return
     */
    public static long getSDTotal() {

        if (ExistSDCard()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs mStatFs = new StatFs(path.getPath());
            long blockSize = mStatFs.getBlockSize();
            long totalBlocks = mStatFs.getBlockCount();
//            return Formatter.formatFileSize(context, blockSize * totalBlocks);
            return blockSize * totalBlocks;
        } else {
            return 0;
        }
    }

    /**
     * 获得SD卡可用大小
     * @return
     */
    public static long getSDAvail() {

        if (ExistSDCard()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs mStatFs = new StatFs(path.getPath());
            long blockSize = mStatFs.getBlockSize();
            long availableBlocks = mStatFs.getAvailableBlocks();
            return blockSize * availableBlocks;
//            return Formatter.formatFileSize(context, blockSize * availableBlocks);
        } else {
            return 0;
        }
    }

    /**
     * 获得TF卡路径
     * @return
     */
    public static String getTFDir(){
        String path = "";
        try {
            InputStream ins= Runtime.getRuntime().exec("mount").getInputStream();
            BufferedReader reader=new BufferedReader(new InputStreamReader(ins));
            String line="";
            while((line=reader.readLine())!=null){
                if(line.contains("sdcard")){
                    if(line.contains("vfat")||line.contains("fuse")){
                        String split[]=line.split(" ");
                        path=split[1];
                    }
                }
            }
            reader.close();
            ins.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{

        }
        return path;
    }

    /**
     * 获得TF卡总大小
     * @return
     */
    public static long  getTFTotal(){
        try{

            if(!"".equals(getTFDir())){
                File base = new File(getTFDir());
                StatFs stat = new StatFs(base.getPath());
                long blockSize = stat.getBlockSize();
                long totalBlocks = stat.getBlockCount();
                return blockSize * totalBlocks;
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获得TF卡可用大小
     * @return
     */
    public static long getTFAvail(){
        try{

            if(!"".equals(getTFDir())){
                File base = new File(getTFDir());
                StatFs stat = new StatFs(base.getPath());
                long blockSize = stat.getBlockSize();
                long availableBlocks = stat.getAvailableBlocks();
                return blockSize * availableBlocks;
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 外部存储(SDCard)是否可用
     * @return
     */
    public static boolean ExistSDCard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    /**
     * 通讯方式
     * @return
     */
    public static String  getCommunicationMode(Context context) {
        ConnectivityManager cm;
        cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isWifitrue = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ? true : false;
        boolean isGprstrue = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ? true : false;
        if(isWifitrue==true){
            return "0";
        }else if(isGprstrue==true){
            return "2";
        }else{
            return "当前无网络连接";
        }

    }

    /**
     * 当前通讯方式IP地址
     * @return
     */
    public static String  getIpAddress(Context context) {

        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络

                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
            return "当前无网络连接";
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    /**
     * 把毫秒转成（HH:mm:ss）
     * @param milliSecondTime
     * @return
     */
    public  static String calculatTime(long milliSecondTime) {

        long hour = milliSecondTime /(60*60*1000);
        long minute = (milliSecondTime - hour*60*60*1000)/(60*1000);
        long seconds = (milliSecondTime - hour*60*60*1000 - minute*60*1000)/1000;

        if(seconds >= 60 )
        {
            seconds = seconds % 60;
            minute+=seconds/60;
        }
        if(minute >= 60)
        {
            minute = minute % 60;
            hour  += minute/60;
        }
        String sh = "";
        String sm ="";
        String ss = "";
        if(hour <10) {
            sh = "0" + String.valueOf(hour);
        }else {
            sh = String.valueOf(hour);
        }
        if(minute <10) {
            sm = "0" + String.valueOf(minute);
        }else {
            sm = String.valueOf(minute);
        }
        if(seconds <10) {
            ss = "0" + String.valueOf(seconds);
        }else {
            ss = String.valueOf(seconds);
        }

        return sh +":"+sm+":"+ ss;
    }

    /**
     * 判断是否有调用权限
     * @return
     */
    public static boolean isRightfulCalling(Context context,String permission){

        PackageManager pm = context.getPackageManager();
        String[] callingApp = pm.getPackagesForUid(Binder.getCallingUid());
        if (null != callingApp && callingApp.length > 0) {
            for (String app: callingApp) {
                Log.i("DeviceUtils","callingApp [] :"+app);
                try {
                    PackageInfo pack = pm.getPackageInfo(app, PackageManager.GET_PERMISSIONS);
                    String[] permissions = pack.requestedPermissions;
                    if (null != permissions && permissions.length > 0) {
                        for (String  str: permissions) {
                            Log.i("DeviceUtils", "permissions [] :" + str);
                            if (permission.equals(str)) {
                                return false;
                            }
                        }
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }

        }
        return true;

    }


}
